package com.topisv.tms.task;

import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.util.HtmlUtils;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.stock.ViewCusStock;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.stock.ViewCusStockService;
import com.topisv.tms.service.task.ScheduledTaskService;
import com.topisv.tms.utils.io.ReaderXML;
import com.topisv.tms.utils.mail.MailSenderInfo;
import com.topisv.tms.utils.mail.SimpleMailSender;

/**
 * 安全预警任务
 *  Date          Author       Version       Description
 * ----------------------------------------------------------
 *  2014-7-22      CC            1.0           Create
 */
@Component
@Lazy(false)
public class CusSafeTask {
	protected Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private ViewCusStockService viewCusStockService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private ScheduledTaskService scheduledTaskService;

	/**
	 * 定时任务,每天7点发送邮件给商家
	 */
	@Scheduled(cron = "0 0 7 * * *")
	public void execute() {
		try {
			try {
				scheduledTaskService.lock();
			} catch (Exception e) {
			}
			boolean rs = scheduledTaskService.check();
			if (rs) {
				log.info("send mail begin.");
				Map<String, Object> emptyMap = Collections.emptyMap();
				Page<ViewCusStock> warningViews = viewCusStockService.loadViewStockWarning(emptyMap, 1, Integer.MAX_VALUE);
				sendMail(warningViews.getContent());
			}
		} catch (Exception e) {
			log.error("some error happened", e);
		}
	}

	private void sendMail(List<ViewCusStock> views) {
		CusSafeData data = new CusSafeData();
		for (ViewCusStock view : views) {
			data.add(view);
		}
		sendMail(data);
	}

	private void sendMail(CusSafeData data) {
		Map<String, String> areaGroupCache = new HashMap<String, String>();
		for (Map.Entry<Customers, List<ViewCusStock>> entry : data.data.entrySet()) {
			Customers key = entry.getKey();
			List<ViewCusStock> value = entry.getValue();
			MailSenderInfo mailInfo = buildMailInfo(buildMailContent(key, value, areaGroupCache), key.getEmail());
			SimpleMailSender.sendHtmlMail(mailInfo);
		}
	}

	private String buildMailContent(Customers custCode, List<ViewCusStock> views, Map<String, String> areaGroupCache) {
		Element root = ReaderXML.read("/template/cus-safe.xml");
		Element bodyElement = root.element("html").element("body");
		// 处理1:
		Element spanElement = bodyElement.element("div");
		spanElement.setText(MessageFormat.format(spanElement.getText(), custCode.getCustomerName()));
		// 处理2：
		Element trElement = bodyElement.element("table").element("tbody").element("tr");
		String contentText = trElement.asXML();
		int index = 0;
		StringBuilder sb = new StringBuilder();
		for (ViewCusStock view : views) {
			sb.append(MessageFormat.format(contentText, ++index, view.getCustomer().getCustomerName(), getCacheGroupName(view.getWarehouseCode(), areaGroupCache), view.getSku(), view.getGoodsName(), view.getSalesNum(), view.getSafeNum()));
		}
		Element tbodyElement = trElement.getParent();
		tbodyElement.remove(trElement);
		tbodyElement.setText(sb.toString());
		return HtmlUtils.htmlUnescape(root.element("html").asXML());
	}

	private String getCacheGroupName(String key, Map<String, String> areaGroupCache) {
		String groupName = areaGroupCache.get(key);
		if (groupName == null) {
			AreaGroup areaGroup = areaGroupService.findByGroupCode(key);
			groupName = areaGroup.getGroupName();
			areaGroupCache.put(key, groupName);
		}
		return groupName;
	}

	private MailSenderInfo buildMailInfo(String content, String toAddress) {
		MailSenderInfo mailInfo = new MailSenderInfo();

		mailInfo.setMailServerHost("smtp.exmail.qq.com");
		mailInfo.setMailServerPort("587");
		mailInfo.setValidate(true);

		mailInfo.setUserName("operation@paiu.com.cn");
		mailInfo.setPassword("paiu2014");

		mailInfo.setFromAddress("operation@paiu.com.cn");
		mailInfo.setToAddress(toAddress.split(","));
		mailInfo.setCcAddress(new String[] { "pengjianguo@paiu.com.cn" });
		mailInfo.setSubject("【重要】关于安全库存");
		mailInfo.setContent(content);
		return mailInfo;
	}

	private class CusSafeData {
		private Map<Customers, List<ViewCusStock>> data = new HashMap<Customers, List<ViewCusStock>>();

		private void add(ViewCusStock view) {
			Customers key = view.getCustomer();
			List<ViewCusStock> views = data.get(key);
			if (views == null) {
				views = new LinkedList<ViewCusStock>();
				data.put(key, views);
			}
			views.add(view);
		}
	}
}
